import esbuild from "esbuild";
import minimist from "minimist";
import { createRequire } from "module";
import { dirname, resolve } from "path";
import { fileURLToPath } from "url";

// node scripts/dev.js reactivity -f esm === process.argv
const args = minimist(process.argv.slice(2)); // 解析命令行参数
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const require = createRequire(import.meta.url);

const target = args._[0] || "reactivity";
const format = args.f || "iife"; // 打包后模块化规范，默认是立即执行函数

const pkg = require(resolve(__dirname, `../packages/${target}/package.json`));
const entry = resolve(__dirname, `../packages/${target}/src/index.ts`);

// 打包
esbuild
  .context({
    entryPoints: [entry], // 入口文件
    outfile: resolve(__dirname, `../packages/${target}/dist/${target}.js`), // 打包后输出文件
    bundle: true, // 打包依赖打包成一个文件
    sourcemap: true, // 生成sourceMap文件
    platform: "browser", // 打包后给浏览器使用
    format, // 打包后模块化规范 cjs esm iife
    globalName: pkg.buildOptions?.name, // 打包后全局变量名
  })
  .then((ctx) => {
    console.log("dev success");

    return ctx.watch(); // 监听文件变化
  });
